package com.story.shiro.authenticator;

import java.util.ArrayList;
import java.util.Collection;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.realm.Realm;

import com.story.web.shiro.token.StoryLoginToken;

public class StoryModularRealmAuthenticator extends ModularRealmAuthenticator {
	@Override
	protected AuthenticationInfo doAuthenticate(
			AuthenticationToken authenticationToken)
			throws AuthenticationException {
		// 判断getRealms()是否返回为空
		assertRealmsConfigured();
		// 强制转换回自定义的StoryLoginToken
		StoryLoginToken token = (StoryLoginToken) authenticationToken;
		// 获取登陆类型，判断是用户还是管理员
		String loginType = token.getLoginType();
		Collection<Realm> realms = getRealms();
		// 登录类型对应的所有Realm
		Collection<Realm> typeRealms = new ArrayList<Realm>();
		for (Realm realm : realms) {
			if (realm.getName().contains(loginType)) {
				typeRealms.add(realm);
			}
		}
		if (typeRealms.size() == 1)
			return doSingleRealmAuthentication(typeRealms.iterator().next(),
					token);
		else
			return doMultiRealmAuthentication(typeRealms, token);
	}

}
